<!-- eslint-disable space-before-function-paren -->
<template>
  <div style="padding: 20px" class="student">
    <!--工具条-->
    <el-form
      ref="searchForm"
      :inline="true"
      :model="searchForm"
      class="demo-form-inline"
    >
      <el-form-item>
        <el-button
          v-if="isStudentList"
          size="mini"
          type="primary"
          @click="$router.push('add')"
        >
          添加学生
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          v-if="isStudentList"
          size="mini"
          type="danger"
          @click="batchRemove"
        >
          批量删除
        </el-button>
      </el-form-item>
      <el-form-item label="学生姓名">
        <el-input
          v-model.trim="searchForm.name"
          size="mini"
          clearable
          placeholder="请输入学生姓名"
          @input="search"
        />
      </el-form-item>
      <el-form-item label="年级">
        <el-select
          v-model.trim="searchForm.class"
          size="mini"
          clearable
          placeholder="请选择年级"
          @change="search"
        >
          <el-option
            v-for="item in classList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="search">搜索</el-button>
      </el-form-item>
    </el-form>
    <!--数据表格-->
    <el-table
      :data="studentList"
      style="width: 100%"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="75" />
      <el-table-column label="序号" width="85">
        <template v-slot="{ $index }">
          <span>{{ (page - 1) * limit + $index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="avatar" label="头像" width="150">
        <template v-slot="{ row }">
          <img :src="row.avatar" style="width: 60%; height: 60%" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="150" />
      <el-table-column prop="sex" label="性别" width="120" />
      <el-table-column label="年级" width="150">
        <template v-slot="{ row }">
          <el-tag :type="getTagType(row.class)">{{
            getClass(row.class)
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="入学时间" width="200">
        <template v-slot="{ row }">
          {{ getEnterTime(row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <div v-if="isStudentList">
            <el-button type="text" size="small" @click="edit(row)">
              编辑
            </el-button>
            <el-button type="text" size="small" @click="del(row)">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      style="text-align: center; margin-top: 15px"
      :current-page="page"
      :page-sizes="[5, 10, 15, 20, total]"
      :page-size="limit"
      layout="prev, pager, next, jumper, ->, total, sizes"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import studentApi from "@/api/student";
import { mapState } from "vuex";
import "animate.css";

export default {
  name: "StudentList",
  data() {
    return {
      // 学生列表
      studentList: [],
      // 选择导出的学生列表
      exportStudentList: [],
      inputWidth: "2",
      total: 0,
      page: 1,
      limit: 5,
      // 0获取未删除的学生列表，1获取已删除的学生列表
      status: 0,
      searchForm: {
        name: "",
        class: "",
        sex: "",
        startTime: "",
        endTime: "",
      },
      // 跳转过来的查询参数
      dashboardParams: {},
      // 批量删除的学生id
      ids: [],
      currentIndex: -1,
      chooseTag: [],
    };
  },
  computed: {
    // 从vuex中获取年级列表
    ...mapState("classL", ["classList"]),
    // 获取年级名称
    getClass() {
      return (classId) => {
        let className = "";
        this.classList.forEach((item) => {
          if (item.id === classId) {
            className = item.name;
          }
        });
        return className;
      };
    },
    // 年级标签样式
    getTagType() {
      return (classId) => {
        let tagType = "";
        if (classId === 1) {
          tagType = "success";
        } else if (classId === 2) {
          tagType = "warning";
        } else if (classId === 3) {
          tagType = "danger";
        } else {
          tagType = "info";
        }
        return tagType;
      };
    },
    // 获取入学时间
    getEnterTime() {
      return (createTime) => {
        const date = new Date(createTime);
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        return year + "-" + month + "-" + day;
      };
    },
    // 判断当前页面是否是学生列表页面
    isStudentList() {
      return this.$route.path.indexOf("list") > 0;
    },
  },
  mounted() {
    // 派发action，获取年级列表
    this.$store.dispatch("classL/getClassList");
    if (this.isStudentList) {
      this.status = 0;
    } else {
      this.status = 2;
    }
    // 获取学生列表
    this.getStudentList();
  },
  methods: {
    // 获取学生列表
    getStudentList() {
      studentApi
        .getStudentList(
          {
            status: this.status,
            page: this.searchForm?.name?.length > 0 ? 1 : this.page,
            pageSize: this.limit,
          },
          this.searchForm
        )
        .then((res) => {
          this.studentList = res.data;
          this.total = res.total;
        })
        .catch();
    },
    // 编辑学生
    edit(row) {
      this.$router.push({ path: "/student/edit/" + row.id });
    },
    // 删除学生
    del(row) {
      this.$confirm("此操作将删除该学生, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          studentApi.deleteStudent(row.id).then((res) => {
            this.$message({
              type: "success",
              message: res.msg,
            });
            this.getStudentList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 搜索学生
    search() {
      // 整理数据 清除空字段
      for (const key in this.searchForm) {
        if (this.searchForm[key] === "") {
          delete this.searchForm[key];
        }
      }
      this.getStudentList();
    },
    // 批量删除学生
    batchRemove() {
      if (this.ids.length === 0) {
        this.$message({
          type: "warning",
          message: "请选择要删除的学生",
        });
        return;
      }
      this.$confirm("此操作将删除选中学生, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          studentApi.batchDeleteStudent(this.ids).then((res) => {
            this.$message({
              type: "success",
              message: res.msg,
            });
            this.getStudentList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 多选框选中事件
    handleSelectionChange(val) {
      this.ids = val.map((item) => item.id);
      this.exportStudentList = val;
    },
    // 表头编辑状态
    changeStatus(e, index) {
      if (this.currentIndex === index) {
        this.currentIndex = -1;
      } else {
        this.currentIndex = index;
      }
      // 输入框的长度
      this.inputWidth = this.$refs.titleInput[index].value.length + 1;
      // 自动聚焦
      this.$nextTick(() => {
        this.$refs.titleInput[index].focus();
      });
    },
    // 表头的编辑状态关闭
    closeEdit() {
      this.currentIndex = -1;
    },
    // 分页大小变化
    handleSizeChange(size) {
      console.log(size);
      this.limit = size;
      this.getStudentList();
    },
    // 当前页变化
    handleCurrentChange(page) {
      this.page = page;
      this.getStudentList();
    },
    // 根据年级名称获取年级id
    getClassId(className) {
      let classId = "";
      this.classList.forEach((item) => {
        if (item.name === className) {
          classId = item.id;
        }
      });
      return classId;
    },
  },
};
</script>

<style scoped>
/*
  el-table样式穿透 表格居中
*/
div/deep/ .el-table th > .cell {
  text-align: center;
}

div/deep/ .el-table .cell {
  text-align: center;
}

/*导出弹出框的输入框*/
div/deep/ .title-input .el-input__inner {
  padding: 0;
}
.location-style {
  cursor: pointer;
}
</style>
